package com.hzy.friend.dao.impl;

import com.google.common.collect.Lists;
import com.hzy.friend.dao.UserDao;
import com.hzy.friend.entity.User;
import com.hzy.friend.utils.MongoDBUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.Arrays;
import java.util.List;

/**
* 请替换User介绍 dao实现类
*
* @author: 请替换作者
* @version: 1.0
* @datetime: 2019-03-01 17:33:27
*/
@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(User user) throws Exception {
        user.setCreateTime(System.currentTimeMillis());
        user.setUpdateTime(System.currentTimeMillis());
        user.setUserId(null);
        mongoTemplate.insert(user);
    }

    @Override
    public void update(User user) throws Exception {
        //查询条件
        Query query = new Query(Criteria.where("_id").is(user.getUserId()));
        //除主键外
        Update update= MongoDBUtils.getUpdateParams(user);
        //更新查询返回结果集的第一条
        mongoTemplate.updateFirst(query,update,User.class);
    }

    @Override
    public void resort(User user) throws Exception {
        String[] ids = user.getIds().split(",");
        for(int i=0; i<ids.length; i++) {
            //过滤参数
            Query query = new Query(Criteria.where("_id").is(ids[i]));
            //修改排序
            Update update= new Update();
            update.set("sortNumber", i);
            mongoTemplate.updateFirst(query,update,User.class);
        }
    }

    @Override
    public User findById(String userId) throws Exception {
        return mongoTemplate.findById(new ObjectId(userId), User.class);
    }

    @Override
    public List<User> find(User user) throws Exception {
        Query query = MongoDBUtils.getQueryByParams(user);
        query.with(Sort.by(Sort.Direction.DESC,"createTime"));
        return mongoTemplate.find(query,User.class);
    }

    @Override
    public void remove(User user) throws Exception {
        List<String> ids = Lists.newArrayList(Arrays.asList(user.getIds().split(",")));
        if(ids.size() > 0){
            Query query=new Query(Criteria.where("_id").in(ids));
            mongoTemplate.remove(query, User.class);
        }
    }

    @Override
    public void remove(String userId) throws Exception {
        Query query=new Query(Criteria.where("_id").is(userId));
        mongoTemplate.remove(query, User.class);
    }
}

